import 'package:airbnb_clone/view/home_page_view/page_detail/create_screen.dart';
import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';

import 'page_detail/chat_screen.dart';
import 'page_detail/favorite_screen.dart';
import 'page_detail/profile_screen.dart';
import '../../widgets/app_nav_bar.dart';
import 'page_detail/home_screen.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final GlobalKey<CurvedNavigationBarState> _navBarKey = GlobalKey();
  final PageController _pageController = PageController();
  int _index = 0;
  bool _ignoreListener = false;

  void onPageTap(int index) {
    _ignoreListener = true;

    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 300), curve: Curves.ease);
    Future.delayed(const Duration(milliseconds: 300), () {
      _ignoreListener = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    _pageController.addListener(() => setState(() {
          if (!_ignoreListener) {
            if (_pageController.page!.round() > _index ||
                _pageController.page!.round() < _index) {
              setState(() {
                _index = _pageController.page!.round();
                _navBarKey.currentState!.setPage(_index);
              });
            }
          }
        }));

    return Scaffold(
      bottomNavigationBar: AppNavBar(
        pageController: _pageController,
        index: _index,
        barKey: _navBarKey,
        onPageTap: onPageTap,
      ),
      body: PageView(
        controller: _pageController,
        children: [
          const HomeScreen()
              .animate(delay: const Duration(microseconds: 500))
              .fade(),
          const FavoriteScreen()
              .animate(delay: const Duration(microseconds: 500))
              .fade(),
          const AddScreen()
              .animate(delay: const Duration(microseconds: 500))
              .fade(),
          const ChatScreen()
              .animate(delay: const Duration(microseconds: 500))
              .fade(),
          const ProfileScreen()
              .animate(delay: const Duration(microseconds: 500))
              .fade()
        ],
      ),
    );
  }
}
